<template>
  <div v-loading="isLoading" class="panel-property">
    <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" :componentStyle="form.componentStyle" />
    <div class="content">
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form haikan-video-unique"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="26%"
        size="default">
        <BaseOption :form="form" option="componentStyle" />
        <BaseOption
          :form="form"
          option="cssStyle.box"
          :df-css-style-attrs="dfCssStyleAttrs.box"
        />
        <el-switch v-model="form.isPreviewVideo"
          style="margin-left: 20px;margin-top: 20px;margin-right: 5px;vertical-align: middle;"></el-switch>
        <span style="display: inline-block;vertical-align: middle;margin-top: 20px;">在编排面是否播放视频</span>
        <section class="video-source-property-setting-box">
          <h3 class="title">海康视频源参数设置</h3>
          <p class="tips">若下拉框中没有您想要的视频源信息，可前往平台维护，<a class="go" href="/metaworks/premiseui/#/parameterConfigManagement" target="_blank">点击前往</a></p>
          <VsFormItem label="" class="selt-item video-source-item" prop="sourceId">
            <el-select v-model="form.sourceId"
              placeholder="---请选择海康视频源---"
              @change="onChangeVideoSourceHandler"
              @visible-change="onListVisibleChangeHandler"
              style="width: 100%;"
              placement="bottom-end">
              <el-option v-for="(item, index) in videoSourceOptions"
                :label="item.label"
                :value="item.value"
                :key="index"></el-option>
            </el-select>
          </VsFormItem>
        </section>
        <section class="extra-property-setting-box">
          <h3 class="title">附加参数</h3>
          <p class="tips">海康综合安防管理平台默认获取视频数据的参数，一般情况下无需调整，除非厂商特别要求。</p>
          <!-- 不显示appkey，为了兼容旧数据，不能去掉不然保存的时候就不传了 -->
          <VsFormItem v-show="false" label="appkey" :helptip="$demoi18n('公钥')">
            <el-input v-model.trim="form.appkey" placeholder="综合安防管理平台提供的appkey"></el-input>
          </VsFormItem>
          <!-- 不显示secret，为了兼容旧数据，不能去掉不然保存的时候就不传了 -->
          <VsFormItem v-show="false" label="secret" :helptip="$demoi18n('密钥')">
            <el-input v-model.trim="form.secret" placeholder="综合安防管理平台提供的secret"></el-input>
          </VsFormItem>
          <!-- 不显示ip，为了兼容旧数据，不能去掉不然保存的时候就不传了 -->
          <VsFormItem v-show="false" label="ip">
            <el-input v-model.trim="form.ip" placeholder="综合安防管理平台IP地址"></el-input>
          </VsFormItem>
          <VsFormItem label="snapDir" :helptip="$demoi18n('抓图存储路径')">
            <el-input v-model.trim="form.snapDir" placeholder="抓图存储路径"></el-input>
          </VsFormItem>
          <VsFormItem label="videoDir" :helptip="$demoi18n('紧急录像或录像剪辑存储路径')">
            <el-input v-model.trim="form.videoDir" placeholder="紧急录像或录像剪辑存储路径"></el-input>
          </VsFormItem>
          <VsFormItem label="iServicePortStart" :helptip="$demoi18n('指定起始端口号')">
            <el-input v-model.trim="form.iServicePortStart" placeholder="指定起始端口号"></el-input>
          </VsFormItem>
          <VsFormItem label="iServicePortEnd" :helptip="$demoi18n('指定结束端口号')">
            <el-input v-model.trim="form.iServicePortEnd" placeholder="指定结束端口号"></el-input>
          </VsFormItem>
          <!-- 不显示监控点编号，为了兼容旧数据，不能去掉不然保存的时候就不传了 -->
          <VsFormItem v-show="false" label="监控点编号">
            <el-input v-model.trim="form.cameraIndexCodes" placeholder="监控点编号,多个用逗号分割"></el-input>
          </VsFormItem>
        </section>
        <section class="display-property-setting-box">
          <h3 class="title">展示样式设置</h3>
          <VsFormItem label="布局">
            <el-select
              v-model="form.videLayout"
              :class="`panel-data-select-${xvueTheme}`"
              :popper-class="`select-poper-${xvueTheme}`"
              @change="generateDeviceList"
              placement="bottom-end">
              <el-option label="1x1" value="1x1"></el-option>
              <el-option label="2x2" value="2x2"></el-option>
              <el-option label="3x3" value="3x3"></el-option>
              <el-option label="4x4" value="4x4"></el-option>
              <el-option label="4x6" value="4x6"></el-option>
              <el-option label="5x5" value="5x5"></el-option>
              <el-option label="1x2" value="1x2"></el-option>
              <el-option label="1x4" value="1x4"></el-option>
              <el-option label="1+2" value="1+2"></el-option>
              <el-option label="1+5" value="1+5"></el-option>
              <el-option label="1+7" value="1+7"></el-option>
              <el-option label="1+8" value="1+8"></el-option>
              <el-option label="1+9" value="1+9"></el-option>
              <el-option label="1+12" value="1+12"></el-option>
              <el-option label="1+16" value="1+16"></el-option>
              <el-option label="4+9" value="4+9"></el-option>
              <el-option label="3+4" value="3+4"></el-option>
              <el-option label="1+1+12" value="1+1+12"></el-option>
            </el-select>
          </VsFormItem>
          <VsFormItem :label="$demoi18n('展示风格')">
            <el-radio-group v-model="form.displayStyle" size="default" :fill="activeColorRadio">
              <el-radio label="icon">图标汇聚</el-radio>
              <el-radio label="flat">平铺展示</el-radio>
            </el-radio-group>
          </VsFormItem>
          <VsFormItem v-if="form.displayStyle === 'icon'" :label="$demoi18n('图标')">
            <IconEditor
              :icon="form.icon"
              :componentStyle="form.componentStyle"
              :rooterWidth="50"
              @save="saveIcon($event, form)"
              @delete="deleteIcon($event, form)"
            />
          </VsFormItem>
          <VsFormItem v-if="form.displayStyle === 'icon'" label="弹窗宽度">
            <el-input v-model.trim="form.popVideoWidth"></el-input>
          </VsFormItem>
          <VsFormItem v-if="form.displayStyle === 'icon'" label="弹窗高度">
            <el-input v-model.trim="form.popVideoHeight"></el-input>
          </VsFormItem>
        </section>
        <section class="device-property-setting-box">
          <h3 class="title">设备列表</h3>
          <VsFormItem label="">
            <el-table :data="deviceList" style="width: 100%" border>
              <el-table-column type="index" width="80" label="序号" align="center" />
              <el-table-column label="设备" align="center">
                <template #default="{ $index }">
                  <el-select v-model="deviceList[$index].channelId"
                    placeholder="请选择"
                    :class="`panel-data-select-${xvueTheme}`"
                    :popper-class="`select-poper-${xvueTheme}`"
                    @visible-change="onDeviceVisibleChangeHandler">
                    <el-option v-for="item in deviceOptions"
                      :label="item.label" :value="item.value"
                      :key="item.value"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="address" label="操作" align="center" width="70">
                <template #default="{ $index }">
                  <el-icon class="icon-up" @click="onMoveUp($index)">
                    <SortUp />
                  </el-icon>
                  <el-icon class="icon-down" @click="onMoveDown($index)">
                    <SortDown />
                  </el-icon>
                </template>
              </el-table-column>
            </el-table>
          </VsFormItem>
        </section>
      </el-form>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import BaseOption from '@/components/common/base-option/base-option.vue';
import Helptip from '@/components/common/helptip/helptip.vue';
import IconEditor from '@/components/common/icon/icon-editor.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import VsFormItem from '@/components/common/vs-form-item/vs-form-item.vue';
import imgUploadBase from '@/mixin/img-upload-base.js';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import apis from '@/apis/hikivision-video.js';
import EventBus from '@/event-bus/EventBus.js';

export default {
  name: 'PanelProperty',
  components: {
    PanelLabelOverflowTooltip,
    IconEditor,
    BaseOption,
    Helptip,
    VsFormItem
  },
  mixins: [panelPropertyBase, imgUploadBase],
  props: ['config', 'widgetInstanceId', 'widget'],
  data() {
    return {
      isLoading: false,
      form: {},
      xvueTheme: window._adoPremise.uc.theme,
      dfCssStyleAttrs: {
        box: {
          backgroundColor: { light: '#fff', dark: '#0d263a', real: '#2E2E2E' },
        },
      },
      videoSourceOptions: [],
      deviceList: [],
      deviceOptions: [],
      rules: {
        sourceId: [
          {
            validator: (rule, value, callback) => {
              const isConfigEvent = this.showEvents.some(e => e.type === 'in' && e.key);

              if (isConfigEvent) {
                return callback();
              }

              if (!value) {
                return callback(new Error('视频源不能为空'));
              }

              return callback();
            }, trigger: ['change', 'blur']
          }
        ]
      },
      showEvents: []
    };
  },
  computed: {
    ...mapState({
      cameraConfigs: state => state.VisualComponentsModule.cameraConfigs,
    }),
    cameraConfig() {
      const emptyConfig = {
        widgetInstanceId: this.widgetInstanceId,
        cameraIndexCodes: '',
      };
      return (this.cameraConfigs && this.cameraConfigs[this.widgetInstanceId]) || emptyConfig;
    },
  },
  created() {
    if (this.config) {
      this.form = JSON.parse(JSON.stringify(this.config.config.property));
      this.generateDeviceList();

      // 选了视频源时调用获取通道列表接口
      if (this.form.sourceId) {
        this.onChangeVideoSourceHandler();
      }

      if (this.cameraConfig.cameraIndexCodes || this.config.config.property.cameraIndexCodes) {
        this.form.cameraIndexCodes = this.cameraConfig.cameraIndexCodes || this.config.config.property.cameraIndexCodes;
        this.form.cameraIndexCodes
          .split(',')
          .forEach((item, index) => {
            this.deviceList[index].channelId = item;
          });
      }
    }

    this.getHikivisionMonitorSourceList();
    EventBus.$on('linkPageEventChange', event => {
      this.showEvents = event;
    });
  },
  beforeUnmount() {
    EventBus.$off('linkPageEventChange');
  },
  beforeDestroy() {
    EventBus.$off('linkPageEventChange');
  },
  methods: {
    getPanelLabelOverflowTooltip() {
      const haikanVideoUnique = this;
      return {
        parentComp: haikanVideoUnique,
      };
    },
    async getHikivisionMonitorSourceList() {
      try {
        const res = await apis.getHikivisionMonitorSourceList();

        if (res.data.code === 200) {
          this.videoSourceOptions = (res.data.data || []).map(item => ({
            label: item.sourceName,
            value: item.sourceId
          }));
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          });
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: error
        });
      }
    },
    async onChangeVideoSourceHandler(initVideoDivide = true) {
      const sourceId = this.form.sourceId;
      const params = {
        sourceId
      };

      if (initVideoDivide) {
        this.generateDeviceList();
      }

      try {
        const res = await apis.getHikivisionMonitorChannelList(params);

        if (res.data.code === 200) {
          this.deviceOptions = res.data.data.map(item => ({
            label: item.channelName,
            value: item.channelId
          }));
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          });
        }
      } catch (error) {
        this.$message({
          type: 'error',
          message: error
        });
      }
    },
    generateDeviceList() {
      const videoLayout = this.form.videLayout;
      let isAdd = videoLayout.indexOf('+') > -1;
      let isMultiply = videoLayout.indexOf('x') > -1;
      let calcUnitList = [];

      if (isAdd) {
        calcUnitList = videoLayout
          .split('+')
          .map(item => Number(item));
      }

      if (isMultiply) {
        calcUnitList = videoLayout
          .split('x')
          .map(item => Number(item));
      }

      const rows = calcUnitList.reduce((prev, next) => {
        if (isAdd) {
          return prev + next;
        }

        if (isMultiply) {
          return prev * next;
        }

        return prev;
      });

      this.deviceList = [];
      
      for (let i = 0; i < rows; i++) {
        this.deviceList.push({
          channelId: ''
        });
      }
    },
    onMoveUp(index) {
      if (this.deviceList.length > 1 && index > 0) {
        [this.deviceList[index - 1], this.deviceList[index]] = [this.deviceList[index], this.deviceList[index - 1]];
      }
    },
    onMoveDown(index) {
      if (this.deviceList.length > 1 && index < this.deviceList.length - 1) {
        [this.deviceList[index + 1], this.deviceList[index]] = [this.deviceList[index], this.deviceList[index + 1]];
      }
    },
    getCameraIndexCodes() {
      return this.deviceList
        .map(({ channelId }) => channelId)
        .join(',');
    },
    onListVisibleChangeHandler(event) {
      // 当展开下拉框时调用获取视频源列表
      if (event) {
        this.getHikivisionMonitorSourceList();
      }
    },
    onDeviceVisibleChangeHandler(event) {
      if (event) {
        if (this.form.sourceId) {
          this.onChangeVideoSourceHandler(false);
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import '../../common/less/panel-property.less';
</style>
<style lang="less" scoped>
.panel-property {
  .content {
    .prop-form {
      padding-left: 4px;
      padding-right: 2px;

      :deep(.el-form-item) {
        margin-bottom: 8px !important;
      }

      :deep(.el-form-item__label) {
        line-height: 36px !important;
      }

      .video-source-property-setting-box,
      .extra-property-setting-box,
      .display-property-setting-box,
      .device-property-setting-box {
        margin-top: 20px;
        margin-left: 20px;

        .title {
          margin: 0;
          padding: 0;
          font-size: 14px;
          font-weight: 550;
          font-family: "Microsoft YaHei", "微软雅黑";
        }

        .tips {
          margin: 0;
          padding: 0;
          font-size: 12px;
          color: #999;

          .go {
            text-decoration: underline;
            color: #409eff;
            cursor: pointer;
          }
        }

        &::v-deep(.el-form-item__content) {
          .panel-data-select-light {
            width: 100%;
          }
        }
      }

      .video-source-property-setting-box,
      .device-property-setting-box {
        &::v-deep(.el-form-item__label) {
          display: none;
        }
      }

      .display-property-setting-box,
      .device-property-setting-box {
        .title {
          margin-bottom: 10px;
        }
      }

      .display-property-setting-box  {
        &::v-deep(.icon-editor) {
          width: auto;
          
          .empty_icon {
            border: none;
          }
        }
      }

      .device-property-setting-box {
        .icon-up.el-icon {
          cursor: pointer;
        }

        .icon-down.el-icon {
          cursor: pointer;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
